<?php

namespace App\Models;

use App\Enums\ProductStatus;
use App\Enums\ProductType;
use App\Enums\RightsType;
use App\Enums\TokenStatus;
use BenSampo\Enum\Traits\CastsEnums;

/**
 * @mixin IdeHelperProduct
 */
class Product extends BaseModel
{
    use CastsEnums;

    protected $casts = [
        'status' => ProductStatus::class,
        'type' => ProductType::class,
        'online_time' => 'datetime',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'rights_type' => RightsType::class,
    ];

    protected $appends = [
        'display_price',
    ];

    public function category()
    {
        return $this->belongsTo(ProductCategory::class, 'category_id');
    }

    public function resale_user()
    {
        return $this->belongsTo(FrontendUser::class, 'resale_user_id');
    }

    public function agent()
    {
        return $this->belongsTo(Agent::class);
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public function available_tokens()
    {
        return $this->hasMany(ProductToken::class)->where('status', TokenStatus::INIT);
    }

    public function configs()
    {
        return $this->hasMany(ProductConfig::class, 'contract_address', 'contract_address');
    }

    public function entity()
    {
        return $this->hasOne(RightsEntityProduct::class, 'product_id')->with(['entity']);
    }

    public function getDisplayPriceAttribute()
    {
        return toYuan($this->price);
    }

    public function copyFrom(Product $product)
    {
        $this->asset_id = $product->asset_id;
        $this->name = $product->name;
        $this->store_id = $product->store_id;
        $this->issuer = $product->issuer;
        $this->hold_rights = $product->hold_rights;
        $this->rights_type = $product->rights_type;
        $this->author = $product->author;
        $this->logo_url = $product->logo_url;
        $this->asset_image_url = $product->asset_image_url;
        $this->public_hash = $product->public_hash;
        $this->contract_address = $product->contract_address;
        $this->intro = $product->intro;
        $this->description = $product->description;
        $this->publisher_account = $product->publisher_account;
        $this->category_id = $product->category_id;
        $this->agent_id = $product->agent_id;
    }
}
